<template>
  <div>
    <h1>英雄列表</h1>
    <el-table :data="tableData">
      <el-table-column type='index' label="序号" width="140">
      </el-table-column>
      <!-- <el-table-column prop="_id" label="id" width="280">
      </el-table-column> -->
      <el-table-column prop="name" label="英雄名称">
      </el-table-column>
      <el-table-column prop="avatar" label="英雄头像">
      <template slot-scope="scope">
        <img :src="scope.row.avatar" alt="" style="height: 3rem">
      </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <!-- scope.row: 当前行的数据 ._id -->
          <el-button @click="$router.push(`/heroes/edit/${scope.row._id}`)" type="primary" size="small">编辑
          </el-button>
          <el-button @click="remove(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
    };
  },
  methods: {
    async fetch() {
      const res = await this.$http.get("rest/heroes");
      this.tableData = res.data;
    },
    // 删除数据
    async remove(row) {
      this.$confirm(`是否删除 "${row.name}" 英雄?"`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        // 确定要删除数据
        const res = await this.$http.delete(`rest/heroes/${row._id}`);
        if (res.data) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          // 删除完后重新获取当前页面数据
          this.fetch()
        }
      });
    },
  },
  created() {
    this.fetch();
  },
};
</script>